import { formatTime2 } from "./time2.js";

// 星期格式转换 0-6：周日到周六
function weekFormat(e, prefix = "周") {
  switch (e) {
    case 0:
      return prefix + "日";
      break;
    case 1:
      return prefix + "一";
      break;
    case 2:
      return prefix + "二";
      break;
    case 3:
      return prefix + "三";
      break;
    case 4:
      return prefix + "四";
      break;
    case 5:
      return prefix + "五";
      break;
    case 6:
      return prefix + "六";
      break;
    default:
      return "";
      break;
  }
}
// 转换今日的时辰格式
function todayTimeFormat(e) {
  if (e >= 0 && e < 7) {
    return "凌晨";
  } else if (e >= 7 && e < 11) {
    return "上午";
  } else if (e >= 11 && e < 13) {
    return "中午";
  } else if (e >= 13 && e < 18) {
    return "下午";
  } else if (e >= 18 && e < 24) {
    return "晚上";
  } else {
    return "";
  }
}

// 是否显示周几
function isShowWeekDay(time, weekDay) {
  const currentWeekDay = new Date().getDay();
  const dayTime = 1000 * 60 * 60 * 24;
  let yestadoy = getYesterday();
  // 1.当前时间与消息时间相差必须大于2天小于7天
  // 2.当前时间距离本周一相差必须大于2天且小于当前距离周一的天数
  // 3.消息时间不可能是0-周日，因为周日没有给后面时间留空间，不会走这里的逻辑，而是走今天的逻辑
  if (time < yestadoy && weekDay !== 0 && getYesterday(7) < time) {
    return true;
  } else {
    return false;
  }
}

// 仿微信时间显示格式转换 @time 时间戳毫秒
function weChatTimeFormat(time) {
  time = String(time).length == 10 ? Number(time + "000") : Number(time);
  const today = new Date().getTime();
  // 当前时间减去获取到的时间
  const sub = today - time;
  const day = 1000 * 60 * 60 * 24;
  const timeDate = new Date(time);
  const currentYear = new Date().getFullYear();
  const getYear = new Date(time).getFullYear();
  const HHmm = `${formatTime2("hh", timeDate)}:${formatTime2("mm", timeDate)}`;
  const showWeekDay = isShowWeekDay(time);

  if (currentYear > getYear) {
    return `${formatTime2("yyyy年MM月dd日", timeDate)} ${todayTimeFormat(
      timeDate.getHours()
    )} ${formatTime2("hh:mm", timeDate)}`;
  } else if (showWeekDay) {
    return `${weekFormat(timeDate.getDay())} ${todayTimeFormat(
      timeDate.getHours()
    )} ${formatTime2("hh:mm", timeDate)}`;
  } else if (time < getToday() && time > getYesterday()) {
    return `昨天 ${HHmm}`;
  } else if (time > getToday()) {
    return `${todayTimeFormat(timeDate.getHours())} ${formatTime2(
      "hh:mm",
      timeDate
    )}`;
  } else {
    return `${formatTime2("MM月dd日", timeDate)} ${todayTimeFormat(
      timeDate.getHours()
    )} ${formatTime2("hh:mm", timeDate)}`;
  }
}

// 获取昨天零点时间戳或指定几天前
function getYesterday(num = 1) {
  let date = new Date(new Date().toLocaleDateString()).getTime();
  date = date - 24 * 60 * 60 * 1000 * num;
  return date;
}
// 获取今天时间戳
function getToday() {
  let date = new Date(new Date().toLocaleDateString()).getTime();
  return date;
}

export { weChatTimeFormat };
